#!/usr/bin/python3
from datetime import datetime
from pathlib import Path
from typing import List, Optional

from pydantic import BaseModel, ValidationError


class User(BaseModel):
    id: int  # 必填
    name: str = "jack ma"  # 默认值
    signup_ts: Optional[datetime] = None  # 选填
    friends: List[int] = []  # 列表中元素是int类型或可以直接转换成int类型


external_data = {
    "id": "123",
    "signup_ts": "2022-12-22 12:22",
    "friends": [1, 2, "3"]
}

user = User(**external_data)
print(repr(user.signup_ts))
print(user.signup_ts)
print(user.id, user.friends)
print(user.dict())
# print(user.model_dump())

print("\033[32m2. --- 检验失败处理 ---\033[0m")
try:
    User(id=1, signup_ts=datetime.today(), friends=[1, 2, "not number"])
except ValidationError as e:
    print(e.json())

print("\033[32m2. --- 模型类的属性和方法 ---\033[0m")
print(user.dict())
print(user.json())
print(user)
print(user.copy())  # 浅复制
# parse_obj/raw是类方法，也是实例方法；类方法更合理
print(User.parse_obj(obj=external_data))
print(user.parse_raw('{"id": 1234, "name": "john snow", "signup_ts": "2022-12-22T12:22:00", "friends": [1, 2, 3]}'))
path = Path('pydantic_tutorial.json')
path.write_text('{"id": 1234, "name": "john snow", "signup_ts": "2022-12-22T12:22:00", "friends": [1, 2, 3]}')
print(User.parse_file(path))
# 打印比json更多元信息
print(user.schema())
print(user.schema_json())
data = {"id": 1234, "name": "john snow", "signup_ts": "2022-12-22T12:22:00", "friends": ["1a", 2, 3]}
# 不检验，直接创建模型数据；不建议使用
print(User.construct(**data))

# 字段顺序问题
print(User.__fields__.keys()) # 定义模型类时，所有字段都注明类型，字段顺序就不会乱

# “\033”引导非常规字符序列
print("\033[32m4. --- 递归模型 ---\033[0m")
#class Sound(BaseModel):